package com.wanglemei.mail.util;


import java.util.Date;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

import org.apache.log4j.Logger;
import org.springframework.util.Assert;

import com.wanglemei.util.EmailUtils;

public class SendMail
{

	private static Logger logger = Logger.getLogger(SendMail.class);
	private String mailServer, username, password;
	private Session mailSession;
	private Properties prop;
	private Message message;

	/**
	 * // 设置邮件服务器相关
	 * 
	 * @param mailServer
	 *            :
	 * @param username
	 *            :
	 * @param password
	 *            :
	 */
	public SendMail(String mailServer, String username, String password)
	{
		this.mailServer = mailServer;
		this.username = username;
		this.password = password;
	}
	
	
	public SendMail(String username,String password)
	{
		this.username=username;
		this.password=password;
	}

	/**
	 * 
	 * @param to
	 *            :
	 * @param mailSubject
	 *            :
	 * @param mailContent
	 */
	public void send(String to, String mailSubject, String mailContent)
	{
		EmailAuthenticator mailauth = new EmailAuthenticator(username, password);
		// 设置邮件服务器
		prop = System.getProperties();
		prop.put("mail.smtp.auth", "true");
		prop.put("mail.smtp.host", mailServer);
		prop.put("mail.smtp.port", 25);
		// 产生新的Session服务
		mailSession = mailSession.getDefaultInstance(prop, (Authenticator) mailauth);
		message = new MimeMessage(mailSession);

		try
		{
			   String[] as={"41054472@qq.com"};
			   String[] as1={"271323576@qq.com"};
			message.setFrom(new InternetAddress(username, "淘宝网")); // 设置发件人
			message.setRecipients(Message.RecipientType.TO, getAddress(as));// 设置收件人
			message.setRecipients(Message.RecipientType.CC, getAddress(as1));// 设置收件人
		   
			message.setSubject(mailSubject);// 设置主题
			// message.setContent(mailContent, "text/plain");// 设置内容,中文乱码，用下面的方法

			// 设置内容
			Multipart multipart = new MimeMultipart();
			MimeBodyPart mimeBodyPart = new MimeBodyPart();
			mimeBodyPart.setText(mailContent);
			// mimeBodyPart.setFileName(MimeUtility.encodeText(mailContent,
			// "GBK", "B")); //对邮件头采用base64方式编码
			multipart.addBodyPart(mimeBodyPart);
			message.setContent(multipart);

			// 设置日期
			message.setSentDate(new Date());
			Transport tran = mailSession.getTransport("smtp");
			tran.connect(mailServer, username, password);
			tran.send(message, message.getAllRecipients());
			tran.close();
		} catch (Exception e)
		{
			logger.error(to + "--Failed to send mail.", e);
		}
	}
	
	public void send(String to, String mailSubject, String mailContent, EmailServer emailServer)
	{
		EmailAuthenticator mailauth = new EmailAuthenticator(username, password);
		// 设置邮件服务器
		prop = System.getProperties();
		prop.put("mail.smtp.auth", "true");
		prop.put("mail.smtp.host", emailServer.getHost());
		prop.put("mail.smtp.port", emailServer.getPort());
		// 产生新的Session服务
		mailSession = mailSession.getDefaultInstance(prop, (Authenticator) mailauth);
		message = new MimeMessage(mailSession);

		try
		{
		//	List<E>
		//   String[] as={"41054472@qq.com","271323576@qq.com"};
			
			//getAddress(as);
			//Address[] address=new Address[2]{(new InternetAddress("271323576@qq.com"),};
			message.setFrom(new InternetAddress(username, "淘宝网")); // 设置发件人
			message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));// 设置收件人
      		//	message.setRecipient(Message.RecipientType.TO, new InternetAddress("41054472@qq.com"));// 设置收件人
		//	message.setRecipients(Message.RecipientType.TO,getAddress(as));
			message.setSubject(mailSubject);// 设置主题
			// message.setContent(mailContent, "text/plain");// 设置内容,中文乱码，用下面的方法

			// 设置内容
			Multipart multipart = new MimeMultipart();
			MimeBodyPart mimeBodyPart = new MimeBodyPart();
			mimeBodyPart.setText(mailContent);
			// mimeBodyPart.setFileName(MimeUtility.encodeText(mailContent,
			// "GBK", "B")); //对邮件头采用base64方式编码
			multipart.addBodyPart(mimeBodyPart);
			message.setContent(multipart);

			// 设置日期
			message.setSentDate(new Date());
			Transport tran = mailSession.getTransport("smtp");
			tran.connect(mailServer, username, password);
			Address[] add=message.getAllRecipients();
			tran.send(message, message.getAllRecipients());
			tran.close();
		} catch (Exception e)
		{
			logger.error(to + "--Failed to send mail.", e);
			e.printStackTrace();
		}
	}

	public static boolean send(String to, String mailSubject, String mailContent, EmailServer emailServer, EmailAuthenticator mailauth)
	{
		// 设置邮件服务器
		Properties prop = System.getProperties();
		prop.put("mail.smtp.auth", "true");
		prop.put("mail.smtp.host", emailServer.getHost());
		prop.put("mail.smtp.port", emailServer.getPort());
		// 产生新的Session服务
		Session mailSession = Session.getDefaultInstance(prop, (Authenticator) mailauth);
		Message message = new MimeMessage(mailSession);
		try
		{
			message.setFrom(new InternetAddress(mailauth.getUsername(), "淘宝网")); // 设置发件人
			message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));// 设置收件人
			message.setSubject(mailSubject);// 设置主题
			// message.setContent(mailContent, "text/plain");// 设置内容,中文乱码，用下面的方法
			// 设置内容
			Multipart multipart = new MimeMultipart();
			MimeBodyPart mimeBodyPart = new MimeBodyPart();
			mimeBodyPart.setText(mailContent);
			// mimeBodyPart.setFileName(MimeUtility.encodeText(mailContent,
			// "GBK", "B")); //对邮件头采用base64方式编码
			multipart.addBodyPart(mimeBodyPart);
			message.setContent(multipart);
			// 设置日期
			message.setSentDate(new Date());
			Transport tran = mailSession.getTransport("smtp");
			tran.connect(emailServer.getHost(), mailauth.getUsername(), mailauth.getUserpass());
			tran.send(message, message.getAllRecipients());
			tran.close();
			return true;
		} catch (Exception e)
		{
			logger.error(to + "--Failed to send mail.", e);
			e.printStackTrace();
		}
		
		return false;
	
	}
	
	public static InternetAddress[] getAddress(String[] to) throws MessagingException {
		Assert.notNull(to, "To address array must not be null");
		InternetAddress[] addresses = new InternetAddress[to.length];
		for (int i = 0; i < to.length; i++) {
			addresses[i] = parseAddress(to[i]);
		}
		return addresses;
	}
	

	private static  InternetAddress parseAddress(String address) throws MessagingException {
		InternetAddress[] parsed = InternetAddress.parse(address);
		if (parsed.length != 1) {
			throw new AddressException("Illegal address", address);
		}
		InternetAddress raw = parsed[0];
	
		 return raw;
		
	}

	public static void main(String[] args)
	{
	/*	SendMail mail;
		for (int i = 0; i < 1; i++)
		{
			mail = new SendMail("smtp.126.com", "gy007123@126.com", "guoyang0903");
			// mail = new SendMailByPassWord("hymagic.gotoip4.com",
			// "gy007123@126.com", "guoyang0903");
			System.out.println("sending......");
			mail.send("271323576@qq.com", "出错原因", "未知错误");
			System.out.println("finished!----------------" + i);
			try
			{
				Thread.sleep(500);
			} catch (InterruptedException e)
			{
				e.printStackTrace();
			}

		}
		*/
		
		EmailServer emailServer = EmailServer.getEmailServerByAddress("163.com");
		

		//	boolean flag = iSendMailService.sendMail(to, mailSubject, mailContent, emailServer, new EmailAuthenticator(fromMailList.get(i), PASS_WORD));
		boolean flag = SendMail.send("41054472@qq.com", "测试邮件", "测试邮件", emailServer, new EmailAuthenticator("wanglemei3@163.com", "wanglemei123"));


	}
}